<script setup lang="ts">
import type { cascadeParam } from "@fl/api/add-elevator-api/model/apply-model";
import {
useGetCascadeData,
useReformInstallationProjectAudit,
useReformInstallationProjectSave
} from "@fl/api/elevator-api";
import { SubmitBtn } from "@fl/components";
import FlUpload from "@fl/components/fl-upload.vue";
import { useMessage } from "@fl/hooks/web/use-message"; // 确认框
import { useUserStoreWithOut } from "@fl/store/modules/user";
import { cloneDeep } from "lodash-es";

const userStore = useUserStoreWithOut();
const enterpriseTypeName = userStore.getOrgInfo?.enterpriseTypeName ?? "";
const isArea = computed(
  () =>
    userStore.getOrgInfo?.enterpriseAccount != "4201" &&
    enterpriseTypeName == "市住更局(电梯加装)"
);
const visible = defineModel<boolean>("visible", { required: true });
const isReadonly = defineModel<boolean>("flag", { required: true, default: false });
const detail = defineModel<any>("detail", { required: true, default: {} });

const title = ref<string>("新增");
const formRef = ref();
const { createConfirmModal } = useMessage();
const form = ref({
  longitude: "",
  latitude: "",
});
const initialState = {
  areaCode: isArea.value ? userStore.getOrgInfo?.enterpriseAccount : "",
  areaName: "",
  id: "",
  streetCode: "",
  streetName: "",
  communityCode: "", // 查询传code，提交传id
  communityName: "",
  projectCode: "",
  projectName: "",
  addressInfo: "",
  auditResult: null,
  simpleName: "",
};
const state = ref(cloneDeep(initialState));

const isLoading = ref<boolean>(false);
// 级联选择
const initialParams = {
  targetLabel: isArea.value ? "street" : "area",
  areaCode: isArea.value ? userStore.getOrgInfo?.enterpriseAccount : "",
  streetCode: "",
  communityCode: "",
  time: undefined, // 刷新用，每次选择后都调用接口
};
const areaParams = ref<cascadeParam>(cloneDeep(initialParams));
const streetParams = ref<cascadeParam>(cloneDeep(initialParams));
const communityParams = ref<cascadeParam>(cloneDeep(initialParams));

const isProjectFocus = ref<boolean>(false);

areaParams.value.targetLabel = "area";

// 详情
function getApplyShow() {
  title.value = isReadonly.value ? "核实" : "编辑";
  state.value = cloneDeep(detail.value) ;
  state.value.addressInfo =cloneDeep(detail.value.addressInfo===null?'':detail.value.addressInfo) 
  // 查街道
  streetParams.value.targetLabel = "street";
  streetParams.value.areaCode = state.value.areaCode;
  // 查社区
  communityParams.value.targetLabel = "community";
  communityParams.value.streetCode = state.value.streetCode;
}

watchEffect(() => {
  if (detail.value?.id) {
    getApplyShow();
  }
});

watch(
  () => visible.value,
  () => {
    if (visible.value) {
      reset();
    }
  }
);

const areaOptions = ref<any>();
const streetOptions = ref<any>();
const communityOptions = ref<any>();

const { data: areaList } = useGetCascadeData(areaParams);
const { data: streetList } = useGetCascadeData(streetParams);
const { data: communityList } = useGetCascadeData(communityParams);

watchEffect(() => {
  if (areaList.value) {
    areaOptions.value = cloneDeep(areaList.value);
  }
  if (streetList.value) {
    streetOptions.value = cloneDeep(streetList.value);
  }
  if (communityList.value) {
    communityOptions.value = cloneDeep(communityList.value);
  }
});

const isStreetDisabeld = computed(() => {
  return !state.value.areaCode || isReadonly.value;
});

const isCommunityDisabeld = computed(() => {
  return isStreetDisabeld.value || !state.value.streetCode || isReadonly.value ;
});
// 清空街道
function clearStreet() {
  state.value.streetCode = "";
  state.value.streetName = "";
  clearCommunity();
}

// 清空社区
function clearCommunity() {
  state.value.communityCode = "";
  state.value.communityName = "";
}

// 1.选择区
function areaChange() {
  //清空
  state.value.streetCode = "";
  state.value.communityCode = "";
  clearStreet();

  const target = areaOptions.value.find((v: any) => v.value === state.value.areaCode);
  console.log("target", target);
  state.value.areaName = target.label;
  streetParams.value.targetLabel = "street";
  streetParams.value.areaCode = state.value.areaCode;
  streetParams.value.time = new Date().getTime();
  // console.log('streetParams.value', streetParams.value)
}

// 2.街道选择
function streetChange() {
  //清空
  state.value.communityCode = "";
  // state.value.projectName = '' // ?
  clearCommunity();

  const target = streetOptions.value.find((v: any) => v.value === state.value.streetCode);
  state.value.streetName = target.label;
  communityParams.value.targetLabel = "community";
  communityParams.value.streetCode = state.value.streetCode;
  communityParams.value.time = new Date().getTime();
  // console.log('communityParams.value', streetParams.value)
}

// 3.社区选择
function communityChange() {
  const target = communityOptions.value.find(
    (v: any) => v.value === state.value.communityCode
  );
  state.value.communityName = target.label;
}

// 提交表单
const { isPending, mutate } = useReformInstallationProjectSave();
const { isPending:auditPending, mutate:auditMutate } = useReformInstallationProjectAudit();

// 提交
async function submit() {
  const valid = await formRef.value.formInstance.validate();
  if (valid) {
    const params = {
      ...unref(state),
      areaCode: state.value.areaCode || null, // 后端要求传null
      streetCode: state.value.streetCode || null,
      communityId: state.value.communityCode || null,
      projectCode: state.value.projectCode || null,
    };
    if ((state.value?.flag === 3 || state.value?.flag === 2 )&& title.value === "核实") {
      // 二次提醒
      createConfirmModal({
        content: `提交后，本小区${(state.value?.flag === 3&&params.auditResult==1)||state.value?.flag === 2?'将纳入具备加装电梯条件小区范围':'将不纳入加装电梯条件小区'}，是否确认？`,
        onError: () => {
          console.log("操作取消！");
        },
        onSuccess: () => {
          auditMutate(params, {
            onSuccess: () => {
              ElMessage.success("操作成功");
              cancel();
            },
          });
        },
      });
    } else {
      mutate(params, {
        onSuccess: () => {
          ElMessage.success("操作成功");
          cancel();
        },
      });
    }
  }
}

function cancel() {
  visible.value = false;
  reset();
}

function reset() {
  title.value = "新增";
  state.value = cloneDeep(initialState);
  formRef.value?.formInstance.resetFields();
  isProjectFocus.value = false;
  detail.value = {};
}

const columns = computed(() => {
  return [
    {
      label: "所在区",
      prop: "areaCode",
    },
    {
      label: "街道",
      prop: "streetCode",
    },
    {
      label: "社区",
      prop: "communityCode",
    },
    {
      fieldProps: {
        disabled: computed(() => isReadonly.value),
      },
      label: "小区",
      prop: "projectName",
    },
    {
      fieldProps: {
        // disabled: enterpriseTypeName != "信息中心(电梯加装)",
        maxlength: 32,
      },
      label: "小区别名",
      prop: "simpleName",
    },
    {
      fieldProps: {
        disabled: enterpriseTypeName != "信息中心(电梯加装)",
        maxlength: 32,
      },
      // hideInForm: computed(() => enterpriseTypeName != "信息中心(电梯加装)"),
      label: "小区编码",
      prop: "projectCode",
    },
    {
      label: "备注",
      prop: "remarkInfo",
    },
    {
      label: "位置及范围示意图",
      prop: "addressInfo",
    },
    {
      label: "核实结果",
      prop: "auditResult",
      valueType: "radio",
      hideInForm: computed(
        () => enterpriseTypeName != "信息中心(电梯加装)" || state.value.flag != 3
      ),
      options: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 2,
        },
      ],
    },
    {
      label: "不通过原因",
      prop: "reason",
      hideInForm: computed(() => state.value.auditResult != 2 || title.value === "编辑"),
    },
  ];
});

const rules = computed(() => ({
  areaCode: [
    {
      message: "所在区",
      required: true,
    },
  ],
  streetCode: [
    {
      message: "街道",
      required: true,
    },
  ],
  communityCode: [
    {
      message: "社区",
      required: true,
    },
  ],
  projectName: [
    {
      message: "小区",
      required: true,
    },
  ],
  projectCode: [
    {
      message: "小区编码",
      required: enterpriseTypeName === "信息中心(电梯加装)"&&state.value.auditResult==1 ? true : false,
    },
  ],
  auditResult:[
    {
      message: "核实结果",
      required: true,
    },
  ],
  reason:[
    {
      message: "不通过原因",
      required: true,
    },
  ],
  addressInfo: [
    {
      message: "位置及范围示意图",
      required: (state.value?.flag === 3 || title.value == '新增') ? true : false
    },
  ],
}));
</script>

<template>
  <el-drawer v-model="visible" :size="600">
    <template #header>{{ title }}</template>
    <ElSkeleton v-if="isLoading" animated class="mt-20" />

    <template v-else>
      <div class="mt-20 plusform">
        <PlusForm
          ref="formRef"
          v-model="state"
          :columns="columns"
          :label-width="120"
          :rules="rules"
          :has-footer="false"
          :row-props="{ gutter: 20 }"
          style="height: 600px; "
        >
          <template #plus-field-areaCode>
            <el-select
              v-model="state.areaCode"
              placeholder="请选择"
              :disabled="isArea"
              filterable
              @change="areaChange"
            >
              <el-option
                v-for="item in areaOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>

          <template #plus-field-streetCode>
            <el-select
              v-model="state.streetCode"
              placeholder="请选择"
              filterable
              @change="streetChange"
              :disabled="isStreetDisabeld"
            >
              <el-option
                v-for="item in streetOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
          <template #plus-field-communityCode>
            <el-select
              v-model="state.communityCode"
              placeholder="请选择"
              filterable
              @change="communityChange"
              :disabled="isCommunityDisabeld"
            >
              <el-option
                v-for="item in communityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
          <!-- 位置示意图地图版 -->
          <!-- <template #plus-field-map>
                        <div id="mapBox" style="border:1px solid #ddd;width:80%;height:350px;"></div>
                    </template> -->
          <template #plus-field-addressInfo>
            <FlUpload v-model="state.addressInfo" :limit="1" :key="String(detail.id+state.addressInfo)" />
          </template>
        </PlusForm>
      </div>
    </template>

    <template #footer>
      <div class="flex: auto">
        <SubmitBtn type="primary" :loading="isPending" @click="submit"> 提交 </SubmitBtn>

        <el-button @click="cancel"> 取消 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
.plusform {
  // height: 640px;
  overflow-y: auto;
  overflow-x: hidden;
}

.positive {
  position: absolute;
  width: 100%;
  max-height: 160px;
  background: #fff;
  z-index: 10;
  top: 34px;
  left: 0;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 4px;

  .item {
    padding-left: 10px;
    cursor: pointer;
  }

  .item:hover {
    background: #eee;
  }
}

:deep(.el-drawer__body) {
  height: 100%;
}
</style>
